package com.lg.cms.controller.news;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.lg.cms.dto.ShiroUsernamePasswordToken;
import com.lg.cms.utils.Md5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.session.HttpServletSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;


/**
 * @Description: cms
 * @Author: wuyuhang
 * @create: 2020-10-03 08:33
 */
@Controller
public class UserLoginController {
    /**
     * 登录页
     * @return
     */
    @GetMapping("/login")
    public String get(){
        return "news/wyh-test/login";
    }

    /**
     * 登录请求
     * @param session
     * @param username
     * @param password
     * @param code
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public R<?> login(HttpSession session, String username, String password, String code){
        String sessionCode = (String)session.getAttribute("cms_code");
        code = Md5Util.textToMd5(code);
        if(!code.equals(sessionCode)){
            return R.failed("验证码错误");
        }
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return R.failed("用户名或密码不能为空");
        }
        password = Md5Util.textToMd5(password);
        Subject subject = SecurityUtils.getSubject();
        ShiroUsernamePasswordToken token = new ShiroUsernamePasswordToken(username, password, "user");
        try{
            subject.login(token);
            return R.ok(null);
        }catch (Exception e){
            return R.failed("用户名或密码错误");
        }
    }

    @GetMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }
}